package com.example.demo.controller;

import com.example.demo.domain.Girl;
import com.example.demo.domain.Result;
import com.example.demo.service.GirlService;
import com.example.demo.utils.ResultUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * @author 王盼
 * @create 2018-11-19 14:57
 */
@RestController
@RequestMapping("/")
public class GirlController{
  private final static Logger logger =
          LoggerFactory.getLogger(GirlController.class);

  @Autowired
  private GirlService girlService;

  //查询所有女生的信息
  @GetMapping(value = "/girls_all")
  public  List<Girl> girlList(){
    logger.info("girlList");
    return girlService.getAll();
  }
  //查询一个女生的信息
  @GetMapping(value = "/girl/{id}")
  public Girl girlFindOne(@PathVariable("id") Integer id) {
    return girlService.getOneById(id);
  }
  //添加一个女生的信息
  @PostMapping(value = "/save")
  public Result<Girl> girlAdd(@Valid Girl girl,
                              BindingResult bindingResult) {
    //bindingResult用来返回错误信息的，和@Valid一起的
    if (bindingResult.hasErrors()) {
      return ResultUtil.error(1,
              bindingResult.getFieldError().getDefaultMessage());
    }
    //当属性过多是应传入一个对象，然后在下面添加
    girl.setCupSize(girl.getCupSize());
    girl.setAge(girl.getAge());

    return ResultUtil.success(girlService.save(girl));
  }

  //更新一个女生的信息
  @PutMapping(value = "/update/{id}")
  public Object girlUpdate(@PathVariable("id") Integer id,
                           @RequestParam("cupSize") String cupSize,
                           @RequestParam("age") Integer age) {
    Girl girl = new Girl();
    girl.setId(id);
    girl.setCupSize(cupSize);
    girl.setAge(age);
    return (Girl) girlService.save(girl);
  }

  //删除一个女生的信息，通过id来删除
  @DeleteMapping(value = "/delete/{id}")

  public void girlDelete(@PathVariable("id") Integer id) {
    girlService.deleteGirlById(id);
  }

  //通过年龄查询女生列表
  @GetMapping(value = "/girls_by_age/{age}")
  public List<Girl> girlListByAge(@PathVariable("age")
                                          Integer age) {
    return girlService.getGirlListByAge(age);
  }

}

